/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/maximum-subarray-ii
   @Language: C++
   @Datetime: 16-02-09 08:17
   */

class Solution {
public:
	/**
	 * @param nums: A list of integers
	 * @return: An integer denotes the sum of max two non-overlapping subarrays
	 * Tip: left[i] record max-sub in range [0,i];
	 *      right[i] record max-sub in range [i,N);
	 */
	int maxTwoSubArrays(vector<int> nums) {
		// write your code here
		if (nums.size()<2) return 0;
		int N=nums.size(), i, sum, mx;
		vector<int> left(N,0), right(N,0);
		for(sum=i=0, mx=INT_MIN; i<N; ++i){
			sum += nums[i];
			mx = max(mx,sum);
			if(sum<0) sum=0;
			left[i] = mx;
		}
		for(sum=0,i=N, mx=INT_MIN; i--;){
			sum += nums[i];
			mx = max(mx,sum);
			if (sum<0) sum=0;
			right[i] = mx;
		}
		for(i=1, mx=INT_MIN; i<N; ++i)
			mx = max(mx,left[i-1]+right[i]);
		return mx;
	}
};
